%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function result = deTestD(trainD,testD,deTrainD,K)

result = [];
X = [trainD,testD];
N = size(trainD,2);
M = size(testD,2);
% STEP1: COMPUTE PAIRWISE DISTANCES & FIND NEIGHBORS 

X2 = sum(X.^2,1);

distance = repmat(X2,N+M,1)+repmat(X2',1,N+M)-2*X'*X;
distance = (~eye(N+M)) + distance;
[sorted,index] = sort(distance(1:N,:));
neighborhood = index(1:K,:);

% STEP2: SOLVE FOR RECONSTRUCTION WEIGHTS

tol=1e-3; % regularlizer in case constrained fits are ill conditioned

W = zeros(K,1);
for ii=N+1:N+M
	z = X(:,neighborhood(:,ii))-repmat(X(:,ii),1,K);
	C = z'*z;                                        % local covariance
    C = C + eye(K,K)*tol*trace(C);                   % regularlization (K>D)
    W(:,1) = C\ones(K,1);                           % solve Cw=1
    W(:,1) = W(:,1)/sum(W(:,1));                  % enforce sum(w)=1
    % STEP 3: output
    Y = deTrainD(:,neighborhood(:,ii)')*W;
    result = [result,Y];
end
